package org.jeecg.modules.satff.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.satff.entity.AttendanceClass;
import org.jeecg.modules.satff.entity.AttendanceWorkday;
import org.jeecg.modules.satff.entity.AttendanceGroup;
import org.jeecg.modules.satff.vo.AttendanceGroupPage;
import org.jeecg.modules.satff.service.IAttendanceGroupService;
import org.jeecg.modules.satff.service.IAttendanceClassService;
import org.jeecg.modules.satff.service.IAttendanceWorkdayService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 考勤组
 * @Author: nbacheng
 * @Date:   2024-12-14
 * @Version: V1.0
 */
@Api(tags="考勤组")
@RestController
@RequestMapping("/satff/attendanceGroup")
@Slf4j
public class AttendanceGroupController {
	@Autowired
	private IAttendanceGroupService attendanceGroupService;
	@Autowired
	private IAttendanceClassService attendanceClassService;
	@Autowired
	private IAttendanceWorkdayService attendanceWorkdayService;
	
	/**
	 * 分页列表查询
	 *
	 * @param attendanceGroup
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "考勤组-分页列表查询")
	@ApiOperation(value="考勤组-分页列表查询", notes="考勤组-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(AttendanceGroup attendanceGroup,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AttendanceGroup> queryWrapper = QueryGenerator.initQueryWrapper(attendanceGroup, req.getParameterMap());
		//zhengzao's code - start
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		if(!sysUser.getUsername().equals("admin")){
			queryWrapper.eq("create_by",sysUser.getUsername());
		}
		//zhengzao's code - end
		Page<AttendanceGroup> page = new Page<AttendanceGroup>(pageNo, pageSize);
		IPage<AttendanceGroup> pageList = attendanceGroupService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param attendanceGroupPage
	 * @return
	 */
	@AutoLog(value = "考勤组-添加")
	@ApiOperation(value="考勤组-添加", notes="考勤组-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody AttendanceGroupPage attendanceGroupPage) {
		AttendanceGroup attendanceGroup = new AttendanceGroup();
		BeanUtils.copyProperties(attendanceGroupPage, attendanceGroup);
		if(attendanceGroup.getStaffUids() != null){
			int len  = attendanceGroup.getStaffUids().split(",").length;
			attendanceGroup.setUserNum(len);
		}
		attendanceGroupService.saveMain(attendanceGroup, attendanceGroupPage.getAttendanceClassList(),attendanceGroupPage.getAttendanceWorkdayList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param attendanceGroupPage
	 * @return
	 */
	@AutoLog(value = "考勤组-编辑")
	@ApiOperation(value="考勤组-编辑", notes="考勤组-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<?> edit(@RequestBody AttendanceGroupPage attendanceGroupPage) {
		AttendanceGroup attendanceGroup = new AttendanceGroup();
		BeanUtils.copyProperties(attendanceGroupPage, attendanceGroup);
		AttendanceGroup attendanceGroupEntity = attendanceGroupService.getById(attendanceGroup.getId());
		if(attendanceGroupEntity==null) {
			return Result.error("未找到对应数据");
		}
		if(attendanceGroup.getStaffUids() != null){
			int len  = attendanceGroup.getStaffUids().split(",").length;
			attendanceGroup.setUserNum(len);
		}
		attendanceGroupService.updateMain(attendanceGroup, attendanceGroupPage.getAttendanceClassList(),attendanceGroupPage.getAttendanceWorkdayList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "考勤组-通过id删除")
	@ApiOperation(value="考勤组-通过id删除", notes="考勤组-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		attendanceGroupService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "考勤组-批量删除")
	@ApiOperation(value="考勤组-批量删除", notes="考勤组-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.attendanceGroupService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "考勤组-通过id查询")
	@ApiOperation(value="考勤组-通过id查询", notes="考勤组-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		AttendanceGroup attendanceGroup = attendanceGroupService.getById(id);
		if(attendanceGroup==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(attendanceGroup);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "设定班次通过主表ID查询")
	@ApiOperation(value="设定班次主表ID查询", notes="设定班次-通主表ID查询")
	@GetMapping(value = "/queryAttendanceClassByMainId")
	public Result<?> queryAttendanceClassListByMainId(@RequestParam(name="id",required=true) String id) {
		List<AttendanceClass> attendanceClassList = attendanceClassService.selectByMainId(id);
		return Result.OK(attendanceClassList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "工作日设置通过主表ID查询")
	@ApiOperation(value="工作日设置主表ID查询", notes="工作日设置-通主表ID查询")
	@GetMapping(value = "/queryAttendanceWorkdayByMainId")
	public Result<?> queryAttendanceWorkdayListByMainId(@RequestParam(name="id",required=true) String id) {
		List<AttendanceWorkday> attendanceWorkdayList = attendanceWorkdayService.selectByMainId(id);
		return Result.OK(attendanceWorkdayList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param attendanceGroup
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AttendanceGroup attendanceGroup) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<AttendanceGroup> queryWrapper = QueryGenerator.initQueryWrapper(attendanceGroup, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//zhengzao's code - start
		if(!sysUser.getUsername().equals("admin")){
			queryWrapper.eq("create_by",sysUser.getUsername());
		}
		//zhengzao's code - end
      //Step.2 获取导出数据
      List<AttendanceGroup> queryList = attendanceGroupService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<AttendanceGroup> attendanceGroupList = new ArrayList<AttendanceGroup>();
      if(oConvertUtils.isEmpty(selections)) {
          attendanceGroupList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          attendanceGroupList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<AttendanceGroupPage> pageList = new ArrayList<AttendanceGroupPage>();
      for (AttendanceGroup main : attendanceGroupList) {
          AttendanceGroupPage vo = new AttendanceGroupPage();
          BeanUtils.copyProperties(main, vo);
          List<AttendanceClass> attendanceClassList = attendanceClassService.selectByMainId(main.getId());
          vo.setAttendanceClassList(attendanceClassList);
          List<AttendanceWorkday> attendanceWorkdayList = attendanceWorkdayService.selectByMainId(main.getId());
          vo.setAttendanceWorkdayList(attendanceWorkdayList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "考勤组列表");
      mv.addObject(NormalExcelConstants.CLASS, AttendanceGroupPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("考勤组数据", "导出人:"+sysUser.getRealname(), "考勤组"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<AttendanceGroupPage> list = ExcelImportUtil.importExcel(file.getInputStream(), AttendanceGroupPage.class, params);
              for (AttendanceGroupPage page : list) {
                  AttendanceGroup po = new AttendanceGroup();
                  BeanUtils.copyProperties(page, po);
                  attendanceGroupService.saveMain(po, page.getAttendanceClassList(),page.getAttendanceWorkdayList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
